package com.nbjtjc.safe.util;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.nbjtjc.safe.model.sys.SysFile;
import org.apache.http.client.utils.URLEncodedUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
public class BaiduOCRUtil {
    private static Logger logger = LoggerFactory.getLogger(BaiduOCRUtil.class);

    private int expires_in = 0;

    private String access_token = null;


    @Value("${baidu.api_key}")
    private String api_key;

    @Value("${baidu.secret_key}")
    private String secret_key;

    @Value("${baidu.url}")
    private String url;

    private long expireTime = 0l;
    private SnowflakeIdWorker snowflakeIdWorker;
    @Value("${aliyun.oss.domain}")
    private String ossUrl;

    @PostConstruct
    public void init() {
        //todo 将acess_token 放到redis上去
        this.snowflakeIdWorker = new SnowflakeIdWorker(0, 0);
        JSONObject jsonObject = getAuth(api_key, secret_key);
        if (ObjectUtil.isNotNull(jsonObject)) {
            this.expireTime = new Date().getTime() / 1000 + jsonObject.getIntValue("expires_in");
            this.access_token=jsonObject.getString("access_token");
        } else {
            logger.error("获取access_token失败");
        }
    }

    public String getFileKey(){
        return snowflakeIdWorker.nextId()+"";
    }
    public JSONObject businessLicense(SysFile sysFile) {
        if (new Date().getTime() / 1000 > this.expireTime) {
            this.init();
        }
        try {
            // 本地文件路径
            int index = sysFile.getPath().lastIndexOf("/");
            String encodeFileName = sysFile.getPath().substring(index+1, sysFile.getPath().length());
            String param = "url=https://nbjtjcsafe360.oss-cn-beijing.aliyuncs.com/"  + sysFile.getPath().substring(0, index+1) + URLEncoder.encode(encodeFileName, "UTF-8");


            // 注意这里仅为了简化编码每一次请求都去获取access_token，线上环境access_token有过期时间， 客户端可自行缓存，过期后重新获取。
            String accessToken = "[调用鉴权接口获取的token]";

            String result = HttpUtil.post(url, this.access_token, param);
            logger.info(result);
            return JSONObject.parseObject(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private JSONObject getAuth(String ak, String sk) {
        // 获取token地址
        String authHost = "https://aip.baidubce.com/oauth/2.0/token?";
        String getAccessTokenUrl = authHost
                // 1. grant_type为固定参数
                + "grant_type=client_credentials"
                // 2. 官网获取的 API Key
                + "&client_id=" + ak
                // 3. 官网获取的 Secret Key
                + "&client_secret=" + sk;
        try {
            URL realUrl = new URL(getAccessTokenUrl);
            // 打开和URL之间的连接
            HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.err.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String result = "";
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
            /**
             * 返回结果示例
             */
            logger.info("result" + result);
            JSONObject jsonObject = JSONObject.parseObject(result);
            String access_token = jsonObject.getString("access_token");
            this.expires_in = jsonObject.getIntValue("expires_in");
            return jsonObject;
        } catch (Exception e) {
            logger.error("获取token失败！");
            e.printStackTrace(System.err);
        }
        return null;
    }

    public int getExpires_in() {
        return expires_in;
    }

    public String getAccess_token() {
        return access_token;
    }
}
